package com.oho.viewmodeltest.life;

import android.component.CompatAbility;
import android.component.CompatSlice;
import android.life.extensions.ViewModelProviders;
import android.life.viewmodel.ViewModelProvider;
import android.log.Log;
import com.oho.viewmodeltest.ResourceTable;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;

public class LifeAbilitySlice2 extends CompatSlice {
    private static final String TAG = "LifeAbilitySlice2";
    private NoteViewModel vm;
    private NoteViewModel globalVm;
    private Text tShow;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_life2_request_layout);

        findComponentById(ResourceTable.Id_btn_life).setClickedListener(component -> {
            vm.fetchNotes();
        });

        findComponentById(ResourceTable.Id_btn_life_global).setClickedListener(component -> {
            globalVm.fetchGlobalNotes();
        });

        tShow = (Text) findComponentById(ResourceTable.Id_tv_result);

        initSliceViewModel();
        initGlobalViewModel();
    }

    private void initSliceViewModel(){
        ViewModelProvider provider = ViewModelProviders.of(this);
        vm = provider.get(NoteViewModel.class);
        Log.d(TAG, "slice vm addr:" + vm);

        vm.notes.observe(this, noteModels -> {
            Log.d(TAG, "noteModels:" + noteModels.get(0).content);
            appendtext(noteModels.get(0).content);
        });
    }

    private void initGlobalViewModel(){
        ViewModelProvider globalProvider = ViewModelProviders.of((CompatAbility) getAbility());
        globalVm = globalProvider.get(NoteViewModel.class);

        Log.d(TAG, "global vm addr:" + globalVm);

        globalVm.notes.observe(this, noteModels -> {
            Log.d(TAG, "observe global noteModels:" + noteModels.get(0).content);
            appendtext(noteModels.get(0).content);
        });

        globalVm.notes.observeNoSticky(this, noteModels -> {
            Log.d(TAG, "observeNoSticky global noteModels:" + noteModels.get(0).content);
            appendtext(noteModels.get(0).content);
        });
    }


    private void appendtext(String str) {
        String raw = tShow.getText();
        tShow.setText(raw + "\n" + str);
    }
}
